package com.yumeng.framework.auth.security.authentication;

import com.yumeng.common.api.ApiCode;
import com.yumeng.common.utils.ResponseUtils;
import com.yumeng.framework.auth.bean.LoginTokenInfo;
import com.yumeng.common.auth.BaseAuthInfo;
import com.yumeng.framework.auth.jwt.JwtUtils;
import com.yumeng.framework.auth.security.SecurityAuthHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;

/**
 * 认证成功处理器（Jwt）（用于前后端分离）
 *
 * @author wxd
 * @date 2024/10/9 14:24
 */
public class JwtTokenAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    /**
     * 登录成功后直接返回 JSON
     *
     * @param request the request which caused the successful authentication
     * @param response the response
     * @param authentication the <tt>Authentication</tt> object which was created during
     * the authentication process.
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        BaseAuthInfo authInfo = SecurityAuthHelper.getCurrAuthInfo(authentication);
        LoginTokenInfo tokenInfo = null;
        if (authInfo.getDetails().getAuthClientType() != null){
            tokenInfo = JwtUtils.generateTokenForLogin(authInfo, JwtUtils.getJwtTypeByAuthClientType(authInfo.getDetails().getAuthClientType()), authInfo.getLoginInfo());
        }
        ResponseUtils.writeJson(response, ApiCode.SUCCESS, tokenInfo,"登录成功");
    }



}
